package pkg.drowne.org;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;

public class JoinGame extends Activity implements OnClickListener, Runnable {
	
    // Preference file
    public static final String PREF_FILE = "pf2";
    private SharedPreferences preferences;
    
	private ImageButton availablegameButton;
	private ProgressDialog pd;

	private ListView lv;
	private ArrayAdapter<String> arrayGames;
	
	private String[] GAMESNAME = new String[] {"No games yet."};
	String answer="", user="";
	
	private int[] GAMESID = new int[0];
	private int gameChosen = -1;
	private int gameStage = 0;
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(
        WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.joingame);
        
        registerViews();
        setupOnClickListeners();
      
        arrayGames = new ArrayAdapter<String>(this, R.layout.itemswaitplayersdialog, GAMESNAME);
    	  
        lv = (ListView) findViewById(R.id.listGames);
        lv.setAdapter(arrayGames);
  	 	lv.setTextFilterEnabled(true);
  	 	
  	 	startPD("Fetching game list...", "Please Wait...");
        
        fillDataifExist();
        
    }

    private void fillDataifExist() {

        preferences = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
        user = preferences.getString("username", "");
        
    }
    
    private boolean setPrefsClient() {
		
    	// get the preferences file ready
		preferences = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
		//preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		
		// saves values in the preferences file
		preferences.edit().putBoolean("clientPlayer", true).commit();
		preferences.edit().putBoolean("hostPlayer", false).commit();
		preferences.edit().putInt("idgame", gameChosen).commit();
		
		return true;
	}

    private void registerViews() {
		
    	availablegameButton = (ImageButton)this.findViewById(R.id.available_game_button);
    	
	}

	public void setupOnClickListeners() {
        
		availablegameButton.setOnClickListener(this);
    }
    
    public void onClick(View V) {
    	
    	switch(V.getId()) {
    	
    	case R.id.available_game_button:
//    		Intent locateFriendsIntent = new Intent(this, locate.class);
//    		startActivity(locateFriendsIntent);
    	    gameStage = 0;
    	    startPD("Fetching game list...", "Please Wait...");
    	    
    		break;
    	
    	}

    }

    @Override
    public void run() {
        
        if(gameStage == 0) {
            // Fetch game list

            answer = Connection.getAvailableGames();
            
            if(!answer.equalsIgnoreCase("EMPTY")) {
              
                handler.sendEmptyMessage(1);
                           
            } else {

                handler.sendEmptyMessage(0);
            }
            gameStage = 1;
            
        } else {
            // join game
        	
            int gameSessionID = Connection.joinGame(user, gameChosen);
            
            if(gameSessionID != -1) {
            
                preferences.edit().putInt("gameSessionID", gameSessionID).commit();
                gameStage = 2;
                handler.sendEmptyMessage(2);
                
            } else {
                // error in joining the game
                handler.sendEmptyMessage(-2);
            }
            
        }
        
    }
    
    private void displayGames () {
    	
    	int i = GAMESNAME.length;
    	
    	int i_id = 0; 
    	int i_name = 0;
    	
    	
		Log.d("ARRAY LENGTH", i+"");
		
		String[] results = answer.split("\\|");
		
		// temp arrays
		String[] aux_name = new String[results.length/2];
		int[] aux_id = new int[results.length/2];
		
		// formats results and stores the ids also
		for (int j = 0; j < results.length; j++){	
			
			// saves game id
			if ((j % 2) == 0){
				aux_id[i_id] = Integer.parseInt(results[j]);
				Log.d("FORMATTED IDs", aux_id[i_id] + "");
				i_id++;
				
				
			}
			// saves formatted owner names
			else {
				aux_name[i_name] = results[j] + "'s Game!";	
				Log.d("FORMATTED GAMES", aux_name[i_name]);
				i_name++;
				
				
			}
			 
		}
		
        // activates clicks on list items
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                // gives the index of the game chosen on the list
                gameChosen = GAMESID[position];
                Log.d("GAME CHOSEN", gameChosen + "");

                startPD("Joining game...", "Please Wait...");

            }


  		  });
		
		GAMESNAME = aux_name;
		GAMESID = aux_id;
		
		arrayGames = new ArrayAdapter<String>(this, R.layout.itemswaitplayersdialog, GAMESNAME);
		
		lv.setAdapter(arrayGames);
		
		Log.d("ARRAY", i+"");

    	
    }
    
    
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            pd.dismiss();
            
            switch (msg.what) {
            case 1:
                displayGames();
                break;
                
            case -1:
                Utils.showToastShort(getBaseContext(), "There are no available games at the moment");
                break;
                
            case 0:
                Utils.showToastShort(getBaseContext(), "There are no available games at the moment");
                break;
            
            case 2:
                setPrefsClient(); // stores that the player is a client
                startActivity(new Intent(getBaseContext(), locate.class));
                break;
            
            case -2:
                Utils.showToastShort(getBaseContext(), "An error occurred while joining the game");
                break;
                
            }

        }
    };

    private void startPD(String header, String msg) {
        pd = ProgressDialog.show(this, header, msg, true, false);
        Thread cThread = new Thread(this);
        cThread.start();
        
    }
    
}
